<template>
  <div class="login-mobile">
    <el-form ref="mobileFormRef" :rules="MoblieRules" :model="moblie">
      <el-form-item prop="mobile">
        <el-input v-model="moblie.mobile" placeholder="手机号码" />
      </el-form-item>
      <el-form-item prop="code">
        <el-input v-model="moblie.code" placeholder="验证码">
          <template #append>
            <el-button
              class="moblie-btn"
              type="primary"
              :disabled="btnDisabled"
              @click="sendPhoneClick"
              >{{ sendPhoneText }}</el-button
            >
          </template>
        </el-input>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, reactive } from 'vue'
import { useStore } from '@/store'
import { useRouter } from 'vue-router'
import type { ElForm } from 'element-plus'

import { MoblieRules } from '../config/moblie-config'

import { getSendPhone, postMoblieLogin, getUserInfo } from '@/api/login/login'
import { generateUUID } from '@/utils/global-method'
import { getItem, setItem, removeItem } from '@/utils/storage'

export default defineComponent({
  setup() {
    const store = useStore()
    const router = useRouter()
    const mobileFormRef = ref<InstanceType<typeof ElForm>>()
    const moblie = reactive({
      mobile: getItem('mobile') ?? '',
      code: '',
      randomCode: ''
    })
    // 发送手机验证码
    const sendPhoneText = ref('发送验证码')
    const btnDisabled = ref(false)
    const totalTime = ref(0)
    const sendPhoneClick = () => {
      mobileFormRef.value!.validateField('mobile', async (cb) => {
        if (!cb) {
          moblie.randomCode = generateUUID()
          const res = await getSendPhone({
            mobile: moblie.mobile,
            randomCode: moblie.randomCode
          })
          if (res.code !== '0') return
          totalTime.value = Math.floor((res.data - new Date().getTime()) / 1000)
          if (totalTime.value >= 0) {
            // 倒计时
            const clock = setInterval(() => {
              btnDisabled.value = true
              totalTime.value--
              sendPhoneText.value = `${totalTime.value}s后重新发送`
              if (totalTime.value <= 0) {
                clearInterval(clock)
                btnDisabled.value = false
                sendPhoneText.value = '发送验证码'
                return
              }
            }, 1000)
          }
        }
      })
    }

    // 验证码登录
    const moblieLogin = (isKeepPassword: boolean) => {
      mobileFormRef.value!.validate(async (boolean) => {
        if (boolean) {
          // 记住手机号
          if (isKeepPassword) {
            setItem('mobile', moblie.mobile)
          } else {
            removeItem('mobile')
          }
          // 登录
          const res = await postMoblieLogin(moblie)
          if (res.code === '0') {
            store.commit('login/changeToken', res.data)
            setItem('token', res.data)
          } else {
            return (moblie.code = '')
          }

          // 获取用户信息
          const resp = await getUserInfo()
          if (resp.code !== '0') return
          store.commit('login/changeUserInfo', resp.data)
          setItem('user_info', resp.data)
          router.push('/main')
        }
      })
    }
    return {
      mobileFormRef,
      moblie,
      MoblieRules,
      sendPhoneText,
      btnDisabled,
      sendPhoneClick,
      moblieLogin
    }
  }
})
</script>

<style scoped lang="less">
.login-mobile {
  padding-top: 20px;
  :deep(.el-form-item) {
    .el-input__inner {
      height: 50px;
    }
    .el-input-group__append {
      background-color: white;
      font-size: 13px;
      color: #000;
    }
    .is-disabled {
      border: none;
      background-color: white;
      cursor: pointer;
      color: #c4c9db;
    }
  }
}
</style>
